package com.miguo.framework.view;

import android.app.Dialog;
import android.support.annotation.StringRes;
import android.text.TextUtils;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.content.Context;

import com.miguo.framework.R;

public class LoadingDialog extends Dialog {
    private LinearLayout mLoadingLayout;
    private TextView brandTipTv;
    private String loadTitleSpecial;
    private String[] mBrandTips;
    private Context mContext;
    private LoadingView mLoadingView;
    private boolean isCancelOnTouchOutside = false;

    public LoadingDialog(Context context) {
        super(context, R.style.dialog_style);
        mContext = context;
        initView();
    }

    public LoadingDialog(Context context, int theme) {
        super(context, theme);
        mContext = context;
        initView();
    }

    private void initView() {
        setContentView(R.layout.layer_loading_dialog);
        mLoadingLayout = (LinearLayout) findViewById(R.id.layer_brand_tip_layout);
        brandTipTv = (TextView) findViewById(R.id.tv_brand_tip);
        mLoadingView = (LoadingView) findViewById(R.id.loading_view);
    }

    public void setMessage(String message) {
        loadTitleSpecial = message;
    }

    public void setMessage(@StringRes int messageId){
        loadTitleSpecial = mContext.getString(messageId);
    }

    public void setCanceledOnTouchOutside(boolean cancel) {
        isCancelOnTouchOutside = cancel;
    }

    /**
     * 设置可按回到键可dismiss setCancelable(false) setCancelable(true)
     *
     * @param flag
     */
    public void setCancelable(boolean flag) {
        super.setCancelable(flag);
    }

    public void show() {
        if(mContext != null) {
            mLoadingView.isShowLoading(true);
            setBrandTip();
            super.setCanceledOnTouchOutside(isCancelOnTouchOutside);
            super.show();
        }
    }

    public void dismiss() {
        if(mContext != null) {
            super.dismiss();
            mLoadingView.isShowLoading(false);
            mBrandTips = null;
            loadTitleSpecial = null;
        }
    }

    private void setBrandTip() {
        if (TextUtils.isEmpty(loadTitleSpecial) || "null".equals(loadTitleSpecial)) {
            mBrandTips = mContext.getResources().getStringArray(R.array.brand_tips);
            int tipId = (int) (Math.random() * (double) mBrandTips.length);
            brandTipTv.setText(mBrandTips[tipId]);
            return;
        }
        brandTipTv.setText(loadTitleSpecial);
    }
}
